﻿using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace DCode.EmailValidator.Core.Security
{
    public static class HashHelper
    {
        public static string CalculateMd5Hash(this string input)
        {
            return HashHelper.CalculateHash(input, (HashAlgorithm)MD5.Create());
        }

        public static string CalculateSha1Hash(this string input)
        {
            return HashHelper.CalculateHash(input, (HashAlgorithm)SHA1.Create());
        }

        private static string CalculateHash(string input, HashAlgorithm hashAlgorithm)
        {
            byte[] hash;

            using (var hashAlgorithm1 = hashAlgorithm)
            {
                var bytes = Encoding.ASCII.GetBytes(input);
                hash = hashAlgorithm1.ComputeHash(bytes);
            }

            var stringBuilder = new StringBuilder();

            foreach (var t in hash)
                stringBuilder.Append(t.ToString("X2", (IFormatProvider) CultureInfo.InvariantCulture));
            return stringBuilder.ToString();
        }
    }
}
